import json from "@rollup/plugin-json"
import terser from "@rollup/plugin-terser"
import typescript from "@rollup/plugin-typescript"
import { existsSync, readdirSync, rmSync, statSync } from "fs"
import { join } from "path"
import { defineConfig } from "rollup"
import { fileURLToPath } from "url"

const root = fileURLToPath(new URL(".", import.meta.url))
const outdir = join(root, "out")

// 清空输出目录。
if (existsSync(outdir) && statSync(outdir).isDirectory()) {
  for (const name of readdirSync(outdir)) {
    rmSync(join(outdir, name), { recursive: true })
  }
}

export default defineConfig({
  plugins: [typescript(), terser(), json()],
  external: [/^node:/g, /^@modelcontextprotocol\/sdk\//g, "chalk", "commander"],
  input: join(root, "src", "main.ts"),
  output: {
    dir: outdir,
    format: "esm",
    assetFileNames: "assets/[hash].[ext]",
    chunkFileNames: "chunks/[hash].js",
    entryFileNames: "[name].js",
  },
})
